package com.springboot.study.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springboot.study.common.Result;
import com.springboot.study.entity.User;
import com.springboot.study.service.UserService;
import com.springboot.study.until.RedisUtil;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * @desc 新增单个用户
     * @param user
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody User user) {
        userService.save(user);
        return Result.success();
    }

    /**
     * @desc 修改单个用户
     * @param user
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.updateById(user);
        return Result.success();
    }

    /**
     * @desc 根据id查询单个用户
     * @param id
     * @return
     */
    @GetMapping("/getOne/{id}")
    public Result getOne(@PathVariable Long id) {
        User user = userService.getById(id);
        return Result.success(user);
    }

    /**
     * @desc 查询所有用户
     * @return
     */
    @GetMapping("/getList")
    public Result getList(){
        return Result.success(userService.list());
    }

    /**
     * @desc 删除单个用户
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        userService.removeById(id);
        return Result.success();
    }

    @GetMapping("/page")
    public Result findPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "1") Integer pageSize,
            @RequestParam(defaultValue = "") String name
    ) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if(!"".equals(name)){
            queryWrapper.like(User::getName, name);
        }

        return Result.success(
                userService.page(new Page<>(pageNum, pageSize), queryWrapper)
        );
    }

    @Resource
    private RedisUtil redisUtil;
    @GetMapping("/redis")
    public Result testRedis() {
        List<User> userList = userService.list();
        redisUtil.set("userList", userList);
        // 将结果返回到接口上
        return Result.success(redisUtil.get("userList"));
    }



}
